package com.zuoyeben123.testzybhtml;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.Image;
import android.media.ImageReader;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zuoyeben123.testzybhtml.socket.SocketTransceiver;
import com.zuoyeben123.testzybhtml.socket.TcpClient;
import com.zuoyeben123.testzybhtml.utils.ImageUtils;

import java.nio.ByteBuffer;

/**
 * Created by wangliang on 2017/11/24.
 */

public class TestTpActivity extends AppCompatActivity {

    private static final int STATUS_CONNECT_SUCC = 1;
    private static final int STATUS_CONNECT_FAILED = 2;
    private static final int STATUS_CONNECT_IDEL = 0;

    private static final int TP_SEND = 100;
    private static final int TP_INTERVAL = 1000;

    private TextView mTvStatus;
    private int mStatus = 0;
    private View mainView;
    private ImageView tpView;

    private MediaProjection mediaProjection;
    private VirtualDisplay mVirtualDisplay;
    private MediaProjectionManager mediaProjectionManager;
    private static final int REQUESTRESULT = 0x100;
    private int mWidth;
    private int mHeight;
    private int mScreenDensity;
    private ImageReader mImageReader;


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == TP_SEND) {
                transViewTp();
                handler.sendEmptyMessageDelayed(TP_SEND, TP_INTERVAL);
            }
        }
    };

    private TcpClient client = new TcpClient() {
        @Override
        public void onConnect(SocketTransceiver transceiver) {
            mStatus = STATUS_CONNECT_SUCC;
            refreshStatus();
            handler.sendEmptyMessageDelayed(TP_SEND, TP_INTERVAL);
        }

        @Override
        public void onConnectFailed() {
            mStatus = STATUS_CONNECT_FAILED;
            refreshStatus();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(TestTpActivity.this, "连接创建失败", Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void onReceive(SocketTransceiver transceiver, final byte[] data) {
//            Log.d("WTest", "receive msg:" + Arrays.toString(data));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tpView.setImageBitmap(ImageUtils.byteToBitmap(data));
                }
            });

        }

        @Override
        public void onDisconnect(SocketTransceiver transceiver) {
            mStatus = STATUS_CONNECT_FAILED;
            refreshStatus();
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_tp);

        final EditText et = findViewById(R.id.et_txt);
        mTvStatus = findViewById(R.id.tv_status);
        mainView = findViewById(R.id.main_view);
        tpView = findViewById(R.id.tp_view);


        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                send(et.getText().toString());
                et.setText("");
            }
        });

        initData();

        connect();

    }


    private void initData() {
        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        Display display = getWindowManager().getDefaultDisplay();
        mWidth = display.getWidth();
        mHeight = display.getHeight();
        DisplayMetrics outMetric = new DisplayMetrics();
        display.getMetrics(outMetric);
        mScreenDensity = (int) outMetric.density;
        Intent intent = new Intent(mediaProjectionManager.createScreenCaptureIntent());
        startActivityForResult(intent,REQUESTRESULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mImageReader = ImageReader.newInstance(mWidth,mHeight, PixelFormat.RGBA_8888, 2);
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode,data);
            mVirtualDisplay = mediaProjection.createVirtualDisplay("mediaprojection",mWidth,mHeight,
                    mScreenDensity, DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,mImageReader.getSurface(),null,null);

        }
    }

    /**
     * 发送数据
     */
    private void send(final String str) {
        new Thread(){
            @Override
            public void run() {
                try {
                    Log.d("WLTest", "send msg:" + str);
                    client.getTransceiver().send(str);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /**
     * 设置IP和端口地址,连接或断开
     */
    private void connect() {
        if (client.isConnected()) {
            // 断开连接
            client.disconnect();
        } else {
            try {
                String hostIP = "192.168.20.45";
                int port = Integer.parseInt("10001");
                client.connect(hostIP, port);
            } catch (NumberFormatException e) {
                Toast.makeText(this, "端口错误", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    }

    private void refreshStatus() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(mStatus == STATUS_CONNECT_SUCC) {
                    mTvStatus.setText("连接创建成功");
                } else if(mStatus == STATUS_CONNECT_FAILED) {
                    mTvStatus.setText("连接已经断开");
                } else {
                    mTvStatus.setText("IDEL");
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(client != null) {
            client.disconnect();
        }
        handler.removeCallbacksAndMessages(null);
    }


    private void transViewTp() {
        if(mainView != null) {
            int[] location = new int[2];
            mainView.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            Log.d("test", "Screenx--->" + x + "  " + "Screeny--->" + y);

            mainView.getLocationInWindow(location);
            x = location[0];
            y = location[1];
            Log.d("test", "Window--->" + x + "  " + "Window--->" + y);

            Log.d("test", "left:" + mainView.getLeft());
            Log.d("test", "right:" + mainView.getRight());
            Log.d("test", "Top:" + mainView.getTop());
            Log.d("test", "Bottom:" + mainView.getBottom());
            Log.d("test", "Width:"+mainView.getWidth());
            Log.d("test", "Height:"+mainView.getHeight());
        }

        new Thread(){
            @Override
            public void run() {
                if(mImageReader != null) {
                    long start = System.currentTimeMillis();
                    Image image = mImageReader.acquireLatestImage();
                    if(image != null) {
                        int width = image.getWidth();
                        int height = image.getHeight();
                        final Image.Plane[] planes = image.getPlanes();
                        final ByteBuffer buffer = planes[0].getBuffer();
                        int pixelStride = planes[0].getPixelStride();
                        int rowStride = planes[0].getRowStride();
                        int rowPadding = rowStride - pixelStride * width;
                        Bitmap bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height,
                                Bitmap.Config.ARGB_8888);
                        bitmap.copyPixelsFromBuffer(buffer);
                        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
                        image.close();
                        long end = System.currentTimeMillis();
                        Log.d("WLTest", "crop cusume:" + (end - start));
                        client.getTransceiver().send(ImageUtils.bitmapToByte(ImageUtils.zoomBitmap(bitmap, 720, 1280)));
                        if(bitmap != null && !bitmap.isRecycled()) {
                            bitmap.recycle();
                            bitmap = null;
                        }
                        long sendend = System.currentTimeMillis();
                        Log.d("WLTest", "encode and send cusume:" + (sendend - end));
                    } else {
                        Log.d("WLTest", "not ready.....");
                    }




                }
            }
        }.start();


    }
}
